<script setup lang="ts">
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import Table from '@/components/table/index.vue';
import useManageShip from './useManageShip';
import { addShip, editShip, deleteShip, ShipItem } from '@/services/ship';
import { useAppStore } from '@/store';
import { numValidator } from 'common/src/utils/validator';

const {
  list,
  getList,
  loading,
  total,
  page: pageNo,
  size: pageSize,
} = useManageShip();
const appStore = useAppStore();
const editLoading = ref(false);
const editVisible = ref(false);
const editRow = reactive({
  id: 0,
  mmsi: '',
  name: '',
  type: '',
  len: '',
  beam: '',
  height: '',
  comment: '',
});
const formRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  mmsi: [
    { required: true, message: '请输入舰船号', trigger: ['blur'] },
    { max: 10, message: '最长十位字符', trigger: ['change'] },
    { pattern: /\S+/, message: '请输入舰船号', trigger: ['blur', 'change'] },
  ],
  name: [
    { required: true, message: '请输入舰船名称', trigger: ['blur'] },
    { max: 10, message: '最长十位字符', trigger: ['change'] },
    { pattern: /\S+/, message: '请输入舰船号', trigger: ['blur', 'change'] },
  ],
  type: [
    { required: true, message: '请输入舰船类型', trigger: ['blur'] },
    { max: 3, message: '最长三位字符', trigger: ['change'] },
    { pattern: /\S+/, message: '请输入舰船号', trigger: ['blur', 'change'] },
  ],
  len: [
    { required: true, message: '请输入长', trigger: ['blur'] },
    { validator: numValidator, trigger: ['blur']},
  ],
  beam: [
    { required: true, message: '请输入宽', trigger: ['blur'] },
    { validator: numValidator, trigger: ['blur']},
  ],
  height: [
    { required: true, message: '请输入吃水', trigger: ['blur'] },
    { validator: numValidator, trigger: ['blur']},
  ],
  comment: [
    { max: 100, message: '最长100位字符', trigger: ['change'] },
  ],
});

const handleDeleteRow = async (row: ShipItem) => {
  await ElMessageBox.confirm(`确定删除舰船“${row.shipName}”的配置吗？`, '删除舰船', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  });
  try {
    await deleteShip({ ids: String(row.id) });
    ElMessage({
      type: 'success',
      message: '操作成功',
    });
    handleQuery(1, pageSize.value);
    appStore.updateShipOptions();
  } catch {
    ElMessage({
      type: 'warning',
      message: '操作失败，请重试',
    });
  }
};

const showEditDialog = (row: ShipItem) => {
  formRef.value?.clearValidate();
  editVisible.value = true;
  Object.assign(editRow, {
    id: row.id,
    mmsi: row.mmsi,
    name: row.shipName,
    type: row.shipType,
    len: String(row.lengthM),
    beam: String(row.beamM),
    height: String(row.heightM),
    comment: row.comment,
  });
};

const showAddDialog = () => {
  formRef.value?.clearValidate();
  editVisible.value = true;
  Object.assign(editRow, {
    id: 0,
    mmsi: '',
    name: '',
    type: '',
    len: '',
    beam: '',
    height: '',
    comment: '',
  });
};

const columns = [
  {
    prop: 'index',
    label: '序号',
    align: 'center',
    width: 80,
  },
  {
    prop: 'mmsi',
    label: '舰船号',
    align: 'center',
  },
  {
    prop: 'shipName',
    label: '舰船名称',
    align: 'center',
  },
  {
    prop: 'shipType',
    label: '舰船类型',
    align: 'center',
  },
  {
    prop: 'depart',
    label: '尺寸（长/宽/吃水）',
    align: 'center',
    render: (columnsProps: { row: ShipItem }) => {
      const { lengthM, beamM, heightM } = columnsProps.row;
      return h('span', null, `${lengthM}m / ${beamM}m / ${heightM}m`);
    },
  },
  {
    prop: 'comment',
    label: '备注',
    align: 'center',
    render: (columnsProps: { row: ShipItem }) => {
      const comment = columnsProps.row.comment || '--';
      return h('span', null, comment);
    },
  },
  // {
  //   prop: 'type',
  //   label: '接口类型',
  //   align: 'center',
  // },
  // {
  //   prop: 'times',
  //   label: '调用token次数',
  //   align: 'center',
  // },
  {
    label: '操作',
    align: 'center',
    width: 120,
    // fixed: 'right',
    renderBtns: [
      { text: '编辑', onClick: (_idx: number, row: any) => showEditDialog(row), type: 'primary', link: true },
      { text: '删除', onClick: (_idx: number, row: any) => handleDeleteRow(row), type: 'danger', link: true },
    ]
  }
];

const handleQuery = (page: number, length: number) => {
  getList({ page, length });
};

const handleCancelEdit = () => {
  editVisible.value = false;
};

const handleSaveEdit = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) {
    return;
  }
  editLoading.value = true;
  try {
    const {
      id,
      mmsi,
      name,
      type,
      len,
      beam,
      height,
      comment,
    } = editRow;
    const data = {
      mmsi: mmsi.trim(),
      shipName: name.trim(),
      shipType: type.trim(),
      lengthM: Number(len),
      beamM: Number(beam),
      heightM: Number(height),
      comment,
    }
    if (id === 0) {
      await addShip(data);
    } else {
      await editShip(id, data);
    }
    editVisible.value = false;
    ElMessage({
      type: 'success',
      message: '操作成功',
    });
    appStore.updateShipOptions();
  } catch {
    ElMessage({
      type: 'warning',
      message: '操作失败，请重试',
    });
  } finally {
    handleQuery(1, pageSize.value);
    editLoading.value = false;
  }
};

onMounted(() => {
  handleQuery(1, pageSize.value);
});
</script>

<template>
  <div class="ship-container config-page">
    <div class="page-title">
      <span>系统设置</span>
      <span> / </span>
      <span class="page-title-active">舰船档案</span>
    </div>
    <div class="page-query">
      <ElForm :inline="true">
        <ElFormItem>
          <ElButton type="primary" @click="() => showAddDialog()">+ 添加舰船档案</ElButton>
        </ElFormItem>
      </ElForm>
    </div>
    <div class="page-table-container">
      <Table
        :loading="loading"
        :list="list"
        height="calc(100vh - 35px - 62px - 50px - 40px - 60px)"
        :columns="columns"
        :total="total"
        :page-no="pageNo"
        :page-size="pageSize"
        :get-list="(pageNo: number, pageSize: number) => handleQuery(pageNo, pageSize)"
      />
    </div>
    <ElDialog
      class="custom-dialog"
      v-model="editVisible"
      :title="editRow.id ? '编辑舰船档案' : '添加舰船档案'"
      width="580"
      align-center
      :close-on-click-modal="false"
    >
      <ElForm ref="formRef" :rules="rules" :model="editRow" label-width="90">
        <ElFormItem prop="mmsi" label="舰船号">
          <ElInput placeholder="请输入舰船号" v-model="editRow.mmsi" :disabled="editRow.id !== 0" />
        </ElFormItem>
        <ElFormItem prop="name" label="舰船名称">
          <ElInput placeholder="请输入舰船名称" v-model="editRow.name" />
        </ElFormItem>
        <ElFormItem prop="type" label="舰船类型">
          <ElInput placeholder="请输入舰船类型" v-model="editRow.type" />
        </ElFormItem>
        <ElFormItem class="custom-row-form-item" label-width="0">
          <ElFormItem prop="len" label="长">
            <ElInput
              v-model="editRow.len"
              placeholder="长"
              style="width: 70px;"
            >
              <template #suffix>m</template>
            </ElInput>
          </ElFormItem>
          <ElFormItem prop="beam" label="宽" label-width="40">
            <ElInput
              v-model="editRow.beam"
              placeholder="宽"
              style="width: 70px;"
            >
              <template #suffix>m</template>
            </ElInput>
          </ElFormItem>
          <ElFormItem prop="height" label="吃水" label-width="60">
            <ElInput
              v-model="editRow.height"
              placeholder="吃水"
              style="flex: 1;"
            >
              <template #suffix>m</template>
            </ElInput>
          </ElFormItem>
        </ElFormItem>
        <ElFormItem prop="comment" label="备注">
          <ElInput placeholder="请输入备注" v-model="editRow.comment" type="textarea" :rows="3" resize="none" />
        </ElFormItem>
      </ElForm>
      <div class="dialog-footer">
        <ElButton @click="() => handleCancelEdit()">取消</ElButton>
        <ElButton :loading="editLoading" type="primary" @click="() => handleSaveEdit()">保存</ElButton>
      </div>
    </ElDialog>
  </div>
</template>

<style scoped>
</style>
